package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 自定义定时任务，实现订单状态定时处理
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder() {
        log.info("处理支付超时订单：{}", new Date());
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);

        // 如果查询到了数据，代表存在超时未支付的订单，需要修改订单的状态为 "status = 6"
        if (orders != null && orders.size() > 0) {
            orders.forEach(orders1 -> {
                orders1.setStatus(Orders.CANCELLED);
                orders1.setCancelReason(MessageConstant.THE_ORDER_TIMED_OUT);
                orders1.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders1);
            });
        }
    }

    /**
     * 处理支"派送中"状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("处理支派送中状态的订单:{}", new Date());
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);

        // 如果查询到了数据，代表存在一直派送中的订单，需要修改订单的状态为 "status = 5"
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(time);
                ordersMapper.update(orders);
            });
        }
    }
}
